package com.wei.czz.framework.rabbitMQ.listener;

import com.wei.czz.common.constant.Constant;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.common.messageFlow.MessageStatusEnum;
import com.wei.czz.common.enums.rabbitMQ.MqEnum;
import com.wei.czz.framework.common.entity.MessageFlowEntity;
import com.wei.czz.framework.common.service.MessageFlowService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-05-12 17:42:30
 * className: DeadQueueListener
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class DeadQueueListener {

    private static final Logger log = LoggerFactory.getLogger(DeadQueueListener.class);

    private final MessageFlowService messageFlowService;

    /**
     * 系统已发布博客关联标签变化消息监听方法
     * 根据博客消息，增加或者减少系统已发布博客关联的标签数量
     * @param message mq消息对象
     */
    @RabbitListener(queues = {MqEnum.Queue.DEAD})
    public void blogTagMessage(Message message) {
        String id = message.getMessageProperties().getHeaders().get(Constant.MESSAGE_ID_KEY).toString();
        log.info("死信消息队列消息消费。id={}", id);

        try {
            Long messageId = Long.parseLong(id);
            /*
                修改消息发送记录
             */
            MessageFlowEntity messageFlow = new MessageFlowEntity();
            messageFlow.setId(messageId)
                    .setStatus(MessageStatusEnum.FAIL.getValue())
                    .setUpdateTime(new Date())
                    .setUpdateUser(StringUtils.EMPTY)
                    .setUpdateUserId(CommonEnum.ZERO.getLongValue());
            messageFlowService.saveOrEdit(messageFlow);

        } catch (Exception e) {
            log.error("死信消息消费异常。message={}", e.getMessage(), e);
        }
        log.info("死信消息消费完成");
    }
}
